/**
 * 限制输入特殊字符
 * demo: v-inputNoSpecial="`%$#`"
 */

export default {
  bind: (el, binding, vNode) => {
    let element = el;
    if (element.tagName.toLowerCase() !== "input") {
      element = el.getElementsByTagName("input")[0];
    }

    const setValue = (val) => {
      if (vNode.componentInstance) {
        vNode.componentInstance.$emit("input", val);
      } else {
        element.value = val;
        element.dispatchEvent(new Event("input"));
      }
    };

    if (binding.value) {
      const allSpecialReg = new RegExp(binding.value, "g");
      el.handler = () => {
        if (el.composing) {
          return;
        }
        setValue(element.value.replace(allSpecialReg, ""));
      };
    } else {
      el.handler = () => {};
    }

    el.addEventListener("change", el.handler);

    el.addEventListener("compositionstart", () => {
      el.composing = true;
    });
    el.addEventListener("compositionend", () => {
      el.composing = false;
      el.handler();
    });
  },
  unbind: (el) => el.removeEventListener("change", el.handler),
};
